const { Service } = require('dx-router-admin');
const logsEntity = require('../entity/logs.js');

module.exports = class Logs extends Service {
	constructor(ctx) {
		super(ctx);
		this.entity = logsEntity;
	}
	async myVip(uid) {
		const dbCmd = this.$dx.db.command;
		const $ = this.$dx.db.command.aggregate;
		let { data } = await this.model
			.aggregate()
			.match({
				user_id: uid,
			})
			.project({
				status: 1,
				lock_time: 1,
				go_start_time: 1,
				order_sn: 1,
			})
			.lookup({
				from: 'dx-user-vip-order',
				let: {
					orderSn: '$order_sn',
				},
				pipeline: $.pipeline()
					.match(dbCmd.expr($.eq(['$order_sn', '$$orderSn'])))
					.project({
						vip_price: 1,
					})
					.done(),
				as: 'vip',
			})
			.end();
		return data.map((v) => {
			return {
				...v,
				vip: (v.vip && v.vip[0] && v.vip[0].vip_price) || {},
			};
		});
	}
	async addDate(order) {
		let day = (order.vip_price && order.vip_price.day) || 0;
		const data = {
			vip_id: order.vip_id,
			price: order.amount,
			order_sn: order.order_sn,
			user_id: order.user_id,
			day_num: day,
			excess_time: day * 24 * 60 * 60 * 1000,
			status: 0,
			go_start_time: Date.now(),
		};
		let user = await this.$dx.getUserInfo(order.user_id);
		// 没有vip
		if (!user.vip || !user.vip.expire_time || user.vip.expire_time < Date.now()) {
			await this.$dx.updateUserInfo(order.user_id, {
				vip: {
					vip_id: order.vip_id,
					level: order.level,
					name: order.title,
					expire_time: Date.now() + data.excess_time,
					excess_time: data.excess_time,
					last_start_time: data.go_start_time,
				},
			});
			data.last_start_time = data.go_start_time;
		} else if (user.vip.level === order.level) {
			// 等级相等
			let diffTime = user.vip.excess_time - (Date.now() - user.vip.last_start_time);
			if (diffTime > 0) {
				// 当前的先锁定
				data.status = 1;
				data.lock_time = Date.now();
				// 更新失效时间
				await this.$dx.updateUserInfo(order.user_id, {
					vip: {
						...user.vip,
						expire_time: user.vip.expire_time + data.excess_time,
					},
				});
			} else {
				// 失效了
				await this.$dx.updateUserInfo(order.user_id, {
					vip: {
						vip_id: order.vip_id,
						level: order.level,
						name: order.title,
						expire_time: Date.now() + data.excess_time,
						excess_time: data.excess_time,
						last_start_time: data.go_start_time,
					},
				});
				await this.model.doc(user.vip.vip_id).update({
					status: 3,
					excess_time: 0,
				});
			}
		} else if (user.vip.level < order.level) {
			// 高等级先生效，低等级锁定
			await this.$dx.updateUserInfo(order.user_id, {
				vip: {
					vip_id: order.vip_id,
					level: order.level,
					name: order.title,
					expire_time: Date.now() + day * 24 * 60 * 60 * 1000,
					excess_time: data.excess_time,
					last_start_time: data.go_start_time,
				},
			});
			let diffTime = user.vip.excess_time - (Date.now() - user.vip.last_start_time);
			if (diffTime > 0) {
				// 之前的这个记录
				await this.model.doc(user.vip.vip_id).update({
					status: 1,
					lock_time: Date.now(),
					excess_time: diffTime,
				});
			} else {
				await this.model.doc(user.vip.vip_id).update({
					status: 3,
					excess_time: 0,
				});
			}
		} else if (user.vip.level > order.level) {
			data.status = 1; //锁定
			data.lock_time = Date.now();
		}
		await this.save(data);
	}
	// 定时任务计算vip 过期
	async calculate() {
		let { data } = await this.model
			.where({
				status: 0,
			})
			.field({
				_id: 1,
				user_id: 1,
				day_num: 1,
				status: 1,
				order_sn: 1,
				go_start_time: 1,
				excess_time: 1,
				last_start_time: 1,
				lock_time: 1,
			})
			.limit(50)
			.orderBy('go_start_time', 'asc')
			.get();
		if (!data.length) return;
		const day = 24 * 60 * 60 * 1000;
		let userIds = [];
		for (let item of data) {
			// 过期了
			if (!item.lock_time && item.go_start_time + item.day_num * day < Date.now()) {
				await this.model.doc(item._id).update({
					status: 3,
				});
				userIds.push(item.user_id);
			} else if (item.lock_time && item.excess_time <= Date.now() - item.last_start_time) {
				await this.model.doc(item._id).update({
					status: 3,
				});
				userIds.push(item.user_id);
			}
		}
		if (!userIds.length) return;
		const dbCmd = this.$dx.db.command;
		const $ = this.$dx.db.command.aggregate;
		//一个人不是购买太多的VIP，是可以找完的
		const list = await this.model
			.aggregate()
			.match({
				status: 1,
				user_id: $.in(userIds),
			})
			.lookup({
				from: 'uni-id-users',
				let: {
					user_id: '$user_id',
				},
				pipeline: $.pipeline()
					.match(dbCmd.expr($.eq(['$_id', '$$user_id'])))
					.project({
						vip: 1,
					})
					.done(),
				as: 'user',
			})
			.lookup({
				from: 'dx-user-vip-order',
				let: {
					order_sn: '$order_sn',
				},
				pipeline: $.pipeline()
					.match(dbCmd.expr($.eq(['$order_sn', '$$order_sn'])))
					.project({
						level: 1,
						title: 1,
					})
					.done(),
				as: 'order',
			})
			.end();
		const newList = {};
		list.data.map((item) => {
			if (!newList[item.user_id]) {
				newList[item.user_id] = [item];
			} else {
				newList[item.user_id].push(item);
			}
		});
		for (let item of Object.values(newList)) {
			item.sort((a, b) => {
				return b.order[0].level - a.order[0].level;
			});
			let row = item[0];
			// 第一个
			await this.model.doc(row._id).update({
				status: 0,
			});
			await this.$dx.updateUserInfo(row.user_id, {
				vip: {
					...row.user[0].vip,
					vip_id: row.vip_id,
					level: row.order[0].level,
					name: row.order[0].title,
					excess_time: row.excess_time,
					last_start_time: row.last_start_time,
				},
			});
		}
	}
	user() {
		return this.hasOne('uni-id-users', 'user_id', '_id').field(['nickname', 'avatar']);
	}
};
